package work.mediway.common.util;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @projectName: hos-cdrmp-app
 * @package: work.mediway.common.util
 * @className: PageUtils
 * @author: zhibao
 * @description: TODO
 * @date: 2023/4/23 17:28
 * @version: 1.0
 */
@Component
public class PageUtils2<T> {
    public static <T> IPage<T> pageable(List<T> list, Integer pageNum, Integer pageSize) {

        IPage<T> page = new Page<>();
        if (CollUtil.isEmpty(list)) {
            List<T> collect = new ArrayList<>();
            page.setPages(1);
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            page.setTotal(0);
            page.setRecords(collect);
            return page;
        }
        /**
         * 查list总数
         */
        int total = list.size();

        /**
         * 查总页数
         */
        int totalPage = 0;
        if (total % pageSize == 0) {
            totalPage = total / pageSize;
        } else {
            totalPage = total / pageSize + 1;
        }
        try {
            List<T> collect = list.stream()
                    .skip((pageNum - 1) * pageSize)
                    .limit(pageSize)
                    .collect(Collectors.toList());
            page.setPages(totalPage);
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            page.setTotal(total);
            page.setRecords(collect);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
